import {
  ExecutionContext,
  Injectable,
  UnauthorizedException,
} from '@nestjs/common';
import { AuthGuard } from '@nestjs/passport';
import { ExtractJwt } from 'passport-jwt';
import { verify } from 'jsonwebtoken';
import { ConfigService } from '@nestjs/config';
import { ConfigEnum } from '../enum/config.enum';
import { HttpEnum } from 'src/enum/http.enum';

@Injectable()
export class JwtGuard extends AuthGuard('jwt') {
  constructor(private configService: ConfigService) {
    super();
  }

  async canActivate(context: ExecutionContext): Promise<boolean> {
    const request = context.switchToHttp().getRequest();
    const token = ExtractJwt.fromAuthHeaderAsBearerToken()(request);
    if (!token) {
      throw new UnauthorizedException(HttpEnum.NULL_AUTHORIZATION);
    }
    const data = await verify(
      token,
      this.configService.get(ConfigEnum['JWT.SECRET']),
    );
    if (!data) throw new UnauthorizedException(HttpEnum.IS_LOGIN);

    if (data.exp - data.iat <= 0)
      throw new UnauthorizedException(HttpEnum.LOGIN_EXP);

    const parentCanActivate = (await super.canActivate(context)) as boolean;
    return parentCanActivate;
  }
}
